import React, { useState } from 'react'
import 'antd/dist/antd.css'
import { Card, Input, Button, Spin, message} from 'antd'
import { UserAddOutlined, KeyOutlined } from '@ant-design/icons'
import '../static/css/login.css'
import servicePath from '../config/api'
import axios from 'axios'

function Login(props) {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [isLoading, setIsLoading] = useState(false)

  const checkLogin = () => {
    setIsLoading(true)
    
    if (!username) {
      message.error('用户名不能为空')
      setTimeout(() => {
        setIsLoading(false)
      }, 500)
      return false
    } else if (!password) {
      message.error('密码不能为空')
      setTimeout(() => {
        setIsLoading(false)
      }, 500)
      return false
    }

    let dataProps = {
      username: username,
      password: password
    }

    // axios.post(servicePath.login, dataProps)
    axios({
      method: 'post',
      url: servicePath.login,
      data: dataProps,
      withCredentials: true   // 共享前后端session
    }).then(res => {
      setIsLoading(false)
      if (res.data.data == '登录成功') {
        localStorage.setItem('openId', res.data.openId)
        props.history.push('/index')
      } else {
        message.error('用户名或者密码错误')
      }
    })
  }

  return (
    <div className="login-div">

      <Spin tip="Loading..." spinning={isLoading}>
        <Card 
          title='Heyang blog system' 
          bordered={true}
          style={{width:400}}
        >
          <Input 
            id="username"
            size='large'
            placeholder='Enter your username'
            prefix={<UserAddOutlined style={{color: 'rgba(0,0,0,.25'}} />}
            onChange={(e) => setUsername(e.target.value)}
          />
          <br/><br/>
          <Input.Password
            id="password"
            size='large'
            placeholder='Enter your password'
            prefix={<KeyOutlined style={{color: 'rgba(0,0,0,.25'}} />}
            onChange={(e) => setPassword(e.target.value)}
          />
          <br/><br/>
          <Button type='primary' size="large" block 
            onClick={checkLogin}>
              Login
          </Button>
        </Card>
      </Spin>

    </div>
  )
}

export default Login